package com.zsummer.baikal.common.config.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zsummer.baikal.system.entity.SysUser;
import com.zsummer.baikal.system.service.ISysMenuService;
import com.zsummer.baikal.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Set;
import java.util.stream.Collectors;


/**
 * 从数据库加载用户信息
 * @author zsummer
 * @since 2021/7/28
 */
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final ISysUserService sysUserService;

    private final ISysMenuService SysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        SysUser sysUser = sysUserService.getOne(Wrappers.<SysUser>query().lambda()
                .eq(SysUser::getUsername, username)
                .eq(SysUser::getDelFlag, "0")
        );
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 查询权限
        Set<String> permissions = SysMenuService.findPermissionByUsername(sysUser.getUsername());
        Set<GrantedAuthority> authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
        return new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
    }
}
